package com.food.service.impl;

import com.food.common.Result;
import com.food.mapper.FoodPreferenceMapper;
import com.food.model.UserFoodPreference;
import com.food.service.FoodPreferenceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class FoodPreferenceServiceImpl implements FoodPreferenceService {

    @Autowired
    private FoodPreferenceMapper preferenceMapper;

    @Override
    @Transactional
    public Result<?> addPreference(Integer userId, Integer foodId) {
        if (hasPreference(userId, foodId)) {
            return Result.error("已经收藏过此食物");
        }

        UserFoodPreference preference = new UserFoodPreference();
        preference.setUserId(userId);
        preference.setFoodId(foodId);
        preference.setPreferenceLevel(1);
        preference.setCreatedAt(LocalDateTime.now());
        preference.setUpdatedAt(LocalDateTime.now());

        preferenceMapper.insert(preference);
        return Result.success(null);
    }

    @Override
    @Transactional
    public Result<?> removePreference(Integer userId, Integer foodId) {
        if (!hasPreference(userId, foodId)) {
            return Result.error("未收藏此食物");
        }

        preferenceMapper.delete(userId, foodId);
        return Result.success(null);
    }

    @Override
    public List<UserFoodPreference> getPreferences(Integer userId) {
        return preferenceMapper.findByUserId(userId);
    }

    @Override
    public boolean hasPreference(Integer userId, Integer foodId) {
        return preferenceMapper.exists(userId, foodId);
    }
} 